<?php

namespace App\Admin\Controllers;

use App\Models\ActivityClassArticle;
use App\Models\ArticleModel;
use App\Models\AudioStudy;
use App\Models\BookModel;
use App\Models\BookRecord;
use App\Models\CompanyModel;
use App\Models\CompanyReadModel;
use App\Models\PersonalRead;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Displayers\Actions;
use Encore\Admin\Show;

class ComoanyBookController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '企业书架';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new BookModel());

        $grid->model()->where('company_id', '!=', 0);

        $grid->filter(function ($filter){
            // 去掉默认的id过滤器
            $filter->disableIdFilter();
            $filter->contains('book_title','标题');
        });

        $grid->column('id', __('Id'))->style('display:table-cell;vertical-align:middle;text-align:center;');
        $grid->column('book_title', '标题')->style('display:table-cell;vertical-align:middle;text-align:center;');
        $grid->column('company_id', '公司')->display(function ($company_id){
           return CompanyModel::where('id',$company_id)->value('company_name');
        })->style('display:table-cell;vertical-align:middle;text-align:center;');
        $grid->column('book_logo', '封面')->image('',80,80)->style('display:table-cell;vertical-align:middle;text-align:center;');
        $grid->column('author', '作者')->style('display:table-cell;vertical-align:middle;text-align:center;');
        $grid->column('article_number','章节数')->style('display:table-cell;vertical-align:middle;text-align:center;');

        $grid->column('created_at','创建时间')->style('display:table-cell;vertical-align:middle;text-align:center;');
        $grid->column('updated_at', '更新时间')->style('display:table-cell;vertical-align:middle;text-align:center;');

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(BookModel::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('book_title', '标题');
        $show->field('book_logo', '封面')->image();
        $show->field('author', '作者');
        $show->field('article_number','章节数');

        $show->field('company_id','公司')->as(function ($company_id){
            return CompanyModel::where('id',$company_id)->value('company_name');
        });

        // $show->field('sort_id', __('Sort id'));
        $show->field('created_at','创建时间');
        $show->field('updated_at', '更新时间');

        $show->article('文章', function ($article) {

            $article->setResource('/admin/article-models');

            // 最原始的`按钮图标`形式
            $article->setActionClass(Actions::class);

            $article->filter(function($filter) {
                // 关联查询
                $filter->where(function ($query){
                    $query -> whereHas('book',function ($query){
                        $query -> where('book_title','like',"%".$this -> input."%");
                    });
                },'书本名称');
            });

            $article->id();
            $article->column('id', __('Id'));
            $article->column('article_title','文章标题');

            $article->column('order','排序')->editable();

            $bookModel = new BookModel();
            $article->column('book_id', '所属书本')->display(function ($book_id)use ($bookModel){
                return $bookModel->where('id',$book_id)->value('book_title');
            });
            //$article->column('book.book_logo', '书本封面')->image('', 80, 80);
            //$article->column('article_cover', '背景图')->image('', 180, 180);
            $article->column('created_at', '创建时间');
            $article->column('updated_at', '更新时间');
        });

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new BookModel());

        /* $id = $this ->getKey();
         dd($id);*/

        $form->text('book_title', '标题');

        $form->image('book_logo', '封面')
            ->move('/upload/images/'.date('Y-m-d'))
            ->uniqueName();
        // ->uniqueName();
        $form->select('company_id','公司')
            ->options(
                '/admin/company_list'
            );

        $form->text('author', '作者');

        $form->text('synopsis', '简介');

        $form->select('opend_type','开放权限')
            ->options([
                1 => '全部开放',
                2 => '开放部分公司',
            ])
            ->when('=', 2, function ($form) {
                $form->multipleSelect('book_permission','分配可读公司')
                    ->options(
                        CompanyModel::where('status',3)->pluck('company_name', 'id')
                    );
            });

        $form->saving(function (Form $form) {

            $article = $form->article;
            $new_article = [];
            if(!empty($article)){
                foreach ($article as $k=>$v){
                    $new_article[$k]=$v;
                    $new_article[$k]['company_id'] = $form->company_id;
                }
                $form->article = $new_article;
            }
        });



        $form->deleting(function (Form $form){
            //dd(request()->route()->parameters());
            $article_number = ArticleModel::where('book_id',request()->route()->parameters()['company_book_model'])->count();
            if($article_number>0){
                return response()->json([
                    'status'  => false,
                    'message' => '下面有文章不能刪除,請先刪除对应文章',
                ]);
            }
            //ActivityClassModel AudioStudy PersonalRead CompanyReadModel
            $activity_number = ActivityClassArticle::where('book_id',request()->route()->parameters()['company_book_model'])->count();
            if($activity_number>0){
                return response()->json([
                    'status'  => false,
                    'message' => '六项精进已使用该书本,请先删除活动',
                ]);
            }
       /*     $audio_number = AudioStudy::where('book_id',request()->route()->parameters()['book_model'])->count();
            if($audio_number>0){
                return response()->json([
                    'status'  => false,
                    'message' => '音频学习已使用该书本,请先删除活动',
                ]);
            }*/
            $personalread_number = PersonalRead::where('book_id',request()->route()->parameters()['company_book_model'])->count();
            if($personalread_number>0){
                return response()->json([
                    'status'  => false,
                    'message' => '个人学习已使用该书本,请先删除活动',
                ]);
            }
            $company_number = CompanyReadModel::where('book_id',request()->route()->parameters()['company_book_model'])->count();
            if($company_number>0){
                return response()->json([
                    'status'  => false,
                    'message' => '企业读书已使用该书本,请先删除活动',
                ]);
            }

            //删除对应的阅读记录
            BookRecord::where('book_id',request()->route()->parameters()['company_book_model'])->delete();

        });

        return $form;
    }
}
